package com.leyou.user.interceptor;

import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constant.LyConstants;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProp;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("【用户微服务校验来访服务权限拦截器】开始执行！");
        //获取token
        String token = request.getHeader(LyConstants.SERVER_AUTH_HEADER_KEY);
        //判空
        if(StringUtils.isEmpty(token)){
            log.error("【用户微服务校验来访服务权限拦截器】执行完毕！来访服务被拒！因为没有携带token！");
            //阻止访问处理器
            return false;
        }
        //解析token
        try {
            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), AppInfo.class);
            //获取来访服务可以访问的服务列表
            List<Long> targetList = payload.getUserInfo().getTargetList();
            //判断来访服务是否有访问用户微服务的权限
            if(!targetList.contains(jwtProp.getApp().getId())){
                log.error("【用户微服务校验来访服务权限拦截器】执行完毕！来访服务被拒！请联系管理员获取访问权限！");
                //阻止访问处理器
                return false;
            }
        }catch (Exception e){
            log.error("【用户微服务校验来访服务权限拦截器】执行完毕！来访服务被拒！携带token不合法！");
            //阻止访问处理器
            return false;
        }
        log.info("【用户微服务校验来访服务权限拦截器】执行完毕！来访服务顺利通过！");
        //放行，继续执行处理器
        return true;
    }

}
